using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FiltronASP.Helpers.Pagination.Interfaces;

namespace FiltronASP.Helpers.Pagination
{
    /// <summary>
    /// Klasa zawierajaca metody obslugi listy z paginacja.
    /// </summary>
    public class PagedList<T> : List<T>, IPagedList
    {

        /// <summary>
        /// Konstruktor.
        /// </summary>
        /// <param name="source">zrodlo danych</param>
        /// <param name="pageIndex">numer biezacej strony</param>
        /// <param name="itemsPerPage">liczba elementow na stronie</param>
        public PagedList(IQueryable<T> source, int pageIndex, int itemsPerPage)
        {
            this.ItemsPerPage = itemsPerPage;
            if (pageIndex <= 0)
            {
                pageIndex = 1;
            }   //if
            this.PageIndex = pageIndex;
            this.PagesCount = 0;
            this.ItemsCount = 0;
            if (source != null)
            {
                this.ItemsCount = source.Count();
                this.AddRange(source.Skip((pageIndex - 1) * itemsPerPage).Take(itemsPerPage).ToList());
                if (this.ItemsCount > 0)
                {
                    this.PagesCount = (int)Math.Ceiling((double)this.ItemsCount / (double)this.ItemsPerPage);
                }   //if
            } //if
        }

        /// <summary>
        /// Liczba stron.
        /// </summary>
        public int PagesCount { get; private set; }

        /// <summary>
        /// Liczba elementow kolekcji.
        /// </summary>
        public int ItemsCount { get; private set; }

        /// <summary>
        /// Numer biezacej strony.
        /// </summary>
        public int PageIndex { get; private set; }

        /// <summary>
        /// Liczba elementow na stronie.
        /// </summary>
        public int ItemsPerPage { get; private set; }

        /// <summary>
        /// Czy jest poprzednia strona.
        /// </summary>
        public bool HasPreviousPage
        {
            get 
            {
                if (this.ItemsCount == 0)
                {
                    return false;
                }   //if
                return (this.PageIndex > 1);
            }   //get
        }

        /// <summary>
        /// Czy jest nastepna strona.
        /// </summary>
        public bool HasNextPage
        {
            get
            {
                if (this.ItemsCount == 0)
                {
                    return false;
                }   //if
                return (this.PageIndex * this.ItemsPerPage < this.ItemsCount);
            }   //get
        }

    }

}
